#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import socket
import subprocess

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 2005))
server.listen(3)

conn, addr = server.accept()
while True:
    data = conn.recv(512)

    if data == "exit": exit(3)

    res = subprocess.Popen("{}".format(data.decode("utf-8")), shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    stdout = res.stdout.read()
    stderr = res.stderr.read()
    sub_res = stderr if stderr else stdout
    data_length = len(sub_res)
    conn.send(str(data_length).encode("utf-8"))
    data = conn.recv(1024).decode("utf-8")
    if data == "recv_ready":
        # sendall 完整发送数据。将数据发送到连接的套接字，但在返回之前会尝试发送所有数据。成功返回None
        conn.sendall(sub_res.decode("gbk").encode("utf-8"))

conn.close()
